package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.repository.GoodsRepository
import jakarta.annotation.PostConstruct
import org.springframework.stereotype.Service
import java.util.concurrent.locks.ReentrantLock

@Service
class CompositeGoodsBarcodeGenerator(
    private val goodsRepository: GoodsRepository
) {

    companion object{
        const val PREFIX = "C"
    }
    private var sequence: Int = 0
    private val lock = ReentrantLock()

    @PostConstruct
    fun initSequence() {
        // 获取当前最大序列号
        val maxCompositeBarcode = goodsRepository.findMaxBarcodeByPrefix(PREFIX)
        sequence = maxCompositeBarcode?.let {
            it.substring(PREFIX.length).toIntOrNull() ?: 0
        } ?: 0
    }

    fun generate(): String {
        lock.lock()
        try {
            sequence++
            return "$PREFIX${sequence.toString().padStart(8, '0')}"
        } finally {
            lock.unlock()
        }
    }
}